-- SPDX-License-Identifier: GPL-3.0-or-later

local extension = Package:new("new1")
-- extension.extensionName = "vupslash"
extension.extensionName = "VslTest"
-- extension.game_modes_whitelist = { 'nos_heg_mode', 'new_heg_mode' }
-- dofile "packages/vupslash/game_rule.lua"

-- local VslUtil = require "packages/vupslash/util"
local VslUtil = require "packages/VslTest/util"

--------------------------------------------------
--测试技能：超级英姿
--------------------------------------------------

local super_yingzi = fk.CreateTriggerSkill{
  name = "superyingzi",
  anim_type = "drawcard",
  events = {fk.DrawNCards},
  on_use = function(self, event, target, player, data)
    data.n = data.n + 20
  end,
}

--------------------------------------------------
--测试技能：摸指定牌
--------------------------------------------------

local v_cheat = fk.CreateActiveSkill{
  name = "v_cheat",
  anim_type = "drawcard",
  can_use = function(self, player)
      return true
  end,
  on_use = function(self, room, effect)
      local from = room:getPlayerById(effect.from)
      local cardTypeName = room:askForChoice(from, { 'basic', 'trick', 'equip' }, "cheat")
      local cardType = Card.TypeBasic
      if cardTypeName == 'trick' then
          cardType = Card.TypeTrick
      elseif cardTypeName == 'equip' then
          cardType = Card.TypeEquip
      end

      local allCardIds = Fk:getAllCardIds()
      local allCardMapper = {}
      local allCardNames = {}
      for _, id in ipairs(allCardIds) do
          local card = Fk:getCardById(id)
          if card.type == cardType then
              if allCardMapper[card.name] == nil then
                  table.insert(allCardNames, card.name)
              end

              allCardMapper[card.name] = allCardMapper[card.name] or {}
              table.insert(allCardMapper[card.name], id)
          end
      end

      if #allCardNames == 0 then
          return
      end

      local cardName = room:askForChoice(from, allCardNames, "cheat")
      local toGain = nil
      if #allCardMapper[cardName] > 0 then
          toGain = allCardMapper[cardName][math.random(1, #allCardMapper[cardName])]
      end

      from:addToPile(self.name, toGain, true, self.name)
      room:obtainCard(effect.from, toGain, true, fk.ReasonPrey)
  end
}

--------------------------------------------------
--测试技能：流失体力
--------------------------------------------------

local v_lose = fk.CreateActiveSkill{
  name = "v_lose",
  anim_type = "offensive",
  can_use = function(self, player)
      return true
  end,
  target_num = 1,
  -- card_num = 1,
  card_filter = function(self, to_select, selected, selected_targets)
      return false
      -- if #selected == 1 then return false end
      -- return Fk:currentRoom():getCardArea(to_select) ~= Player.Equip
  end,
  target_filter = function(self, to_select, selected)
      -- local target = Fk:currentRoom():getPlayerById(to_select)
      return #selected == 0
  end,
  on_use = function(self, room, effect)
      local player = room:getPlayerById(effect.from)
      local target = room:getPlayerById(effect.tos[1])
      room:loseHp(target, 1, self.name)
  end,
}

--------------------------------------------------
--娇惰
--技能马克：
-- Q1: 这个技能是什么意思？可以简单概括一下吗？
-- A1: 一般来说是以下效果：
-- ①你可以跳过判定阶段，摸牌阶段结束后弃置两张牌
-- ②你可以跳过摸牌阶段，出牌阶段结束后将手牌数补充至与跳过摸牌阶段时相同
-- ③你可以跳过出牌阶段，弃牌阶段结束后将手牌数补充至与跳过出牌阶段时相同

-- Q2: 至多摸至X张，这个上限会让我弃牌吗？
-- A2: 不会。如至多摸至5张，将手牌从6张调整至10张，则不会摸牌或弃牌。

-- Q3: 【乐不思蜀】对风野慵生效后，跳过摸牌阶段是什么效果？
-- A3: 跳过摸牌阶段与出牌阶段，弃牌阶段结束后将手牌数调整至与摸牌阶段相同。

-- Q4: 濑川绪良发动“奇遇”令风野慵于回合外执行一个出牌阶段，此时用“娇惰”跳过，会发生什么？
-- A4: 于风野慵的下个回合的准备阶段执行后，将手牌数调整至与跳过这个额外出牌阶段时相同。
--------------------------------------------------

local v_jiaoduo = fk.CreateTriggerSkill{
  name = "v_jiaoduo",
  --赋予特殊型技能定义
  anim_type = "special",
  --时机：阶段变化时，阶段结束时
  events = {fk.EventPhaseChanging, fk.EventPhaseEnd},
  --触发条件：
  --（阶段变化时）触发时机的角色为遍历到的角色；遍历到的角色具有本技能；
  --             本回合只使用过一次技能；
  --             被遍历到的角色处于判定/摸牌/出牌阶段；
  --             被遍历到的角色存在对应阶段。
  --（阶段结束时）触发时机的角色为遍历到的角色；遍历到的角色具有本技能；
  --              在上个阶段使用了此技能（通过标记完成）。
  can_trigger = function(self, event, target, player, data)
    if event == fk.EventPhaseChanging then
      local change = data
      --判定区如无牌，则不做判定区处理。
      local cards = {}
      local hand = player:getCardIds(Player.Judge)
      for _,p in ipairs(hand) do
        table.insert(cards, p)
      end
      local x = #(cards)
      return target == player and player:hasSkill(self)
      and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
      and ((change.to == Player.Judge and x > 0) or change.to == Player.Draw or change.to == Player.Play)
      and VslUtil.exist_or_not(player, change.to)
    elseif event == fk.EventPhaseEnd then
      return target == player and player:hasSkill(self)
      and player:getMark("v_jiaoduo_using-turn") > 0
    end
  end,
  on_cost = function(self, event, target, player, data)
    --获取本阶段手牌数，确认是否跳过本阶段。
    if event == fk.EventPhaseChanging then
      local room = player.room
      local change = data
      local prompt = "#v_jiaoduo_choice:::"..VslUtil.phase_string(change.to)..":"..0
      --print(prompt)
      local cards = {}
      local hand = player:getCardIds(Player.Hand)
      for _,p in ipairs(hand) do
        table.insert(cards, p)
      end
      local x = #(cards)
      local draw_limit = 5
      -- local draw_limit = player.maxHp
      if x > 0 then
        if x > draw_limit then
          x = draw_limit
        end
        prompt = "#v_jiaoduo_choice:::"..VslUtil.phase_string(change.to)..":"..x
      end
      if room:askForSkillInvoke(player, self.name, data, prompt) then
      --if VslUtil.yes_or_no(player, self.name, prompt) then
        --尝试了一下，这里不能跳阶段，失败的话只能耦合到on_use了。
        --player:skip(change.to)
        return true
      end
    --满足技能发动要求后，锁定发动。
    elseif event == fk.EventPhaseEnd and (player:getMark("@v_jiaoduo_card-turn") > 0 or player:getMark("@@v_jiaoduo_nocard-turn") > 0) then
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local draw_limit = 5
    -- local draw_limit = player.maxHp
    --以on_cost中跳过阶段为代价，为风野提供标签以触发后续技能。
    --一种标签为无手牌，另一种标签为手牌数，这种区分方式是因为需要将手牌数标签为0的情况视作未触发而非手牌为0.
    if event == fk.EventPhaseChanging then
      local cards = {}
      local hand = player:getCardIds(Player.Hand)
      for _,p in ipairs(hand) do
        table.insert(cards, p)
      end
      local x = #(cards)
      room:setPlayerMark(player, "v_jiaoduo_using-turn", 1)
      if x > 0 then
        room:setPlayerMark(player, "@v_jiaoduo_card-turn", x)
      else
        room:setPlayerMark(player, "@@v_jiaoduo_nocard-turn", 1)
      end
      return true
    elseif event == fk.EventPhaseEnd then
      --清空使用状态，将之前记下来的手牌数转录到local变量z中
      room:setPlayerMark(player, "v_jiaoduo_using-turn", 0)
      local z = 0
      if player:getMark("@@v_jiaoduo_nocard-turn") > 0 then
        room:setPlayerMark(player, "@@v_jiaoduo_nocard-turn", 0)
      elseif player:getMark("@v_jiaoduo_card-turn") > 0 then
        z = player:getMark("@v_jiaoduo_card-turn")
        room:setPlayerMark(player, "@v_jiaoduo_card-turn", 0)
      end
      --现有手牌小于/大于之前记录值之后的处理。
      if player:getHandcardNum() < math.min(draw_limit, z) then
        local a = math.min(draw_limit, z) - player:getHandcardNum()
        player:drawCards(a, self.name)
      elseif player:getHandcardNum() > z then
        local a = player:getHandcardNum() - z
        room:askForDiscard(player, a, a, false, self.name, false)
      end
    end
  end,
}

--------------------------------------------------
--风野慵
--角色马克：
--------------------------------------------------

local fengyeyong_youhemingling = General(extension,"fengyeyong_youhemingling", "individual", 4, 4, General.Female)
fengyeyong_youhemingling:addSkill(v_jiaoduo)

--------------------------------------------------
--神临
--第一张无懈使用之后，同一次无懈询问中，第二张按照原Vup杀会无法使用。
--但在本作中，可能由于无懈可击询问全部结束前，无懈可击尚未进入弃牌堆，导致技能后续才一起生效。
--------------------------------------------------

local v_shenlin = fk.CreateTriggerSkill{
  --（刚需）技能认证名
  name = "v_shenlin",
	mute = true,
  --(非必要）赋予特殊型技能定义
  anim_type = "special",
  --技能为锁定技，满足条件后强制发动
  frequency = Skill.Compulsory,
  --时机：..
  events = {fk.DrawInitialCards, fk.AfterDrawInitialCards, fk.GameStart, fk.AfterCardsMove},
  --触发条件：
	-- ...
  can_trigger = function(self, event, target, player, data)
    if event == fk.DrawInitialCards then
      return target == player and player:hasSkill(self)
    elseif event == fk.AfterDrawInitialCards then
      return target == player and player:hasSkill(self)
    elseif event == fk.GameStart then
      return player:hasSkill(self)
    elseif event == fk.AfterCardsMove then
      for _, move in ipairs(data) do
        if move.toArea == Card.DiscardPile then
          for _, info in ipairs(move.moveInfo) do
            -- local card = Fk:getCardById(info.cardId)
            --这里先不用自动弃牌了，我写的那个自动清空标记的玩意证明了refresh时机估计比现在这个trigger早···
            -- if card:getMark("@@v_shenlin") > 0 then
            if player:getMark("v_shenlin_id_"..info.cardId) > 0 then
              return true
            end
          end
        end
      end
    end
  end,
  --使用流程：
  -- 卡牌移动后：
  --  ...
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.DrawInitialCards then
      room:notifySkillInvoked(player, self.name)
      player:broadcastSkillInvoke(self.name, -1)
      data.num = data.num + 6
    elseif event == fk.AfterDrawInitialCards then
      for _,cd in ipairs(player:getCardIds(Player.Hand)) do
        local card = Fk:getCardById(cd)
        room:setPlayerMark(player, "v_shenlin_id_"..cd, 1)
        room:setCardMark(card, "@@v_shenlin-cm!d*", 1)
      end
    elseif event == fk.GameStart then
      room:notifySkillInvoked(player, self.name)
      player:broadcastSkillInvoke(self.name, -1)
      room:changeMaxHp(player, 6)
    elseif event == fk.AfterCardsMove then
      for _, move in ipairs(data) do
        if move.toArea == Card.DiscardPile then
          for _, info in ipairs(move.moveInfo) do
            -- local card = Fk:getCardById(info.cardId)
            -- if card:getMark("@@v_shenlin") > 0 then
            if player:getMark("v_shenlin_id_"..info.cardId) > 0 then
              -- room:setCardMark(card, "@@v_shenlin", 0)
              room:setPlayerMark(player, "v_shenlin_id_"..info.cardId, 0)
              -- room:setPlayerMark(player, "@@v_shenlin_inidis-turn", 1)
              --等下这里的player要改成持有这个技能，且确认是她拿的神临牌的人
              -- room:notifySkillInvoked(player, self.name)
              local address = "./packages/"..VslUtil.extensionName.."/image/anim/v_lingyuexi"
              room:sendLog{
                type = "#InvokeSkill",
                from = player.id,
                arg = self.name,
              }
              room:setEmotion(player, address)
              player:broadcastSkillInvoke(self.name, -1)
              room:addPlayerMark(player, "@v_shenlin_cost-turn", 1)
              local X = player:getMark("@v_shenlin_cost-turn")
              room:changeMaxHp(player, -X)
            end
          end
        end
      end
    end
  end,
}
local v_shenlin_maxcards = fk.CreateMaxCardsSkill{
  name = "#v_shenlin_maxcards",
  correct_func = function(self, player)
    if player:hasSkill(v_shenlin.name) then
      return 6
    end
  end,
}
v_shenlin:addRelatedSkill(v_shenlin_maxcards)

--------------------------------------------------
--绕梁
--------------------------------------------------

local v_raoliang = fk.CreateTriggerSkill{
  name = "v_raoliang",
  --赋予控制型技能定义
  anim_type = "control",
  --时机：阶段开始时
  events = {fk.EventPhaseStart},
  --触发条件：触发时机的角色为遍历到的角色、遍历到的角色具有本技能，
  -- 遍历到的角色处于结束阶段
  can_trigger = function(self, event, target, player, data)
    --阶段变化时，实现“是否跳出牌”的效果。
    --exist_or_not：用来确认是否跳过对应阶段，类似于以前的Player:isSkipped()
    return target == player and player:hasSkill(self) 
    and player.phase == Player.Finish
  end,
  -- on_trigger = function(self, event, target, player, data)
  --   --if self:isEffectable(player) then
  --   self:doCost(event, target, player, data)
  --   --end
  -- end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local to_return = table.random(VslUtil.getCurrentCenterzone(room), 1)
    local choice = "cancel"
    if #VslUtil.getCurrentCenterzone(room) > 0 then
      local result = room:askForCustomDialog(player, self.name,
      "packages/utility/qml/ChooseCardsAndChoiceBox.qml", {
        VslUtil.getCurrentCenterzone(room),
        {"confirm"},
        "#v_raoliang_choice",
        {"cancel"},
      })
      if result ~= "" then
        local reply = json.decode(result)
        to_return = reply.cards
        choice = reply.choice
      end
      if to_return[1] and to_return[1] ~= -1 then
        self.cost_data = to_return[1]
        return true
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    -- local cid = self.cost_data
    room:moveCards({
      ids = {self.cost_data},
      from = player.id,
      toArea = Card.DrawPile,
      moveReason = fk.ReasonJustMove,
      skillName = self.name,
      drawPilePosition = 1,
  })
  end,
}

--------------------------------------------------
--绫月兮
--角色马克：
--------------------------------------------------

local lingyuexi_youyumushen = General(extension,"lingyuexi_youyumushen", "individual", 3, 4, General.Female)
lingyuexi_youyumushen:addSkill(v_shenlin)
lingyuexi_youyumushen:addSkill(v_raoliang)
  
-- 加载本包的翻译包(load translations of this package)，这一步在本文档的最后进行。
-- dofile "packages/vupslash/i18n/init.lua"
dofile "packages/VslTest/i18n/init.lua"
  
-- return { extension } 

return extension